<script lang="ts" setup>
  import { nextTick, ref } from 'vue';

  import { Page, useVbenDrawer } from '@vben/common-ui';

  import { Button as AButton, Space } from 'ant-design-vue';

  import { useVbenVxeGrid, withDefaultTableConfig, type DrawerStatus } from '#/adapter';
  import { getDeptTree } from '#/api';

  import { columns, flattenTree } from './data';
  import Form from './form.vue';

  const expanded = ref(true);

  const [Table, tableApi] = useVbenVxeGrid(
    withDefaultTableConfig({
      columns,
      treeConfig: {
        parentField: 'pid',
        rowField: 'id',
        transform: true,
        seqMode: 'increasing',
      },
      proxyConfig: {
        ajax: {
          query: async () => {
            const data = await getDeptTree();
            const temp = flattenTree(data);
            return {
              records: temp,
              totalRow: temp.length,
            };
          },
          querySuccess() {
            nextTick(() => {
              expanded.value = true;
              tableApi.grid?.setAllTreeExpand(expanded.value);
            });
          },
        },
      },
    })
      .withTableTitle({
        tableTitle: '部门列表',
      })
      .build(),
  );

  // 树形展开折叠
  const treeToggle = () => {
    expanded.value = !expanded.value;
    tableApi.grid?.setAllTreeExpand(expanded.value);
  };

  // 表单弹框
  const [FormDrawer, drawerApi] = useVbenDrawer({
    connectedComponent: Form,
  });

  // 打开表单操作
  const drawerOpenHandle = (status: DrawerStatus, record?: any) => {
    drawerApi.setData({
      status,
      record: record,
    });
    drawerApi.open();
  };
</script>

<template>
  <Page auto-content-height>
    <Table>
      <template #toolbar-tools>
        <Space>
          <AButton type="primary" @click="drawerOpenHandle('CREATE')"> 新增 </AButton>
          <AButton type="primary" @click="treeToggle">
            {{ expanded ? '折叠全部' : '展开全部' }}
          </AButton>
        </Space>
      </template>
      <template #actions="{ row }">
        <Space>
          <AButton type="link" @click="drawerOpenHandle('VIEW', row)"> 查看 </AButton>
          <AButton type="link" @click="drawerOpenHandle('EDIT', row)"> 编辑 </AButton>
        </Space>
      </template>
    </Table>
    <FormDrawer @reload="tableApi.query" />
  </Page>
</template>
